package com.duomn.mybatis.plugins.parse;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * 
 * @author duomn.hu
 *
 */
public class Insert implements IShardingParser {
	
	private static final String DELIMIT = " \t\n\r\f,"; 

	/**
	 * 解析分表上使用的条件
	 * @return null, 该 sql 不需要分表
	 */
	public Map<String, Map<String, Object>> parse2Condition(String sql, List<Object> params, String tableName){
		String lowSql = sql.toLowerCase();
		String lowTableName = sql.toLowerCase();
		if (lowSql.indexOf(lowTableName) == -1) { // 该sql不需要走分表
			return null;
		}
		
		/*
		 *  insert into tableName(col1, col2, col3) values(val1, val2, val3); 
		 */
		
		int idx_into_idx = lowSql.indexOf("into");
		int idx_col_start = lowSql.indexOf("(");
		String srcTableName = lowSql.substring(idx_into_idx + 4, idx_col_start).trim();
		
		int idx_col_end = lowSql.indexOf(")", idx_col_start);
		String cols = lowSql.substring(idx_col_start + 1, idx_col_end);
		
		StringTokenizer colTokenizer = new StringTokenizer(cols, DELIMIT);
		
		int idx_val_start = lowSql.indexOf("(", idx_col_end);
		int idx_val_end = lowSql.indexOf(")", idx_val_start);
		String vals = lowSql.substring(idx_val_start + 1, idx_val_end);
		StringTokenizer valTokenizer = new StringTokenizer(vals, DELIMIT);
		
		Map<String, Object> conditionMap = new HashMap<String, Object>();
		int i = 0;
		while (colTokenizer.hasMoreTokens()) {
			String col = colTokenizer.nextToken();
			Object val = valTokenizer.nextToken();
			val = "?".equals(val) ? params.get(i++) : val; 
			conditionMap.put(col, val);
		}
		
		Map<String, Map<String, Object>> rst = new HashMap<String, Map<String, Object>>();
		rst.put(srcTableName, conditionMap);
		return rst;
	}
	
}
